
$(document).ready(function(){
    let loginStatus = checkLoginStatus();
    if (loginStatus) {
        // 如果用户已登录，显示登录后的内容，隐藏未登录的内容
          $('#logged-in-content').show();
          $('#logged-out-content').hide();
          $('#username').text(loginStatus);
          checkGeoInfo();
      } else {
        // 如果用户未登录，显示未登录的内容，隐藏登录后的内容
        $('#logged-in-content').hide();
        $('#logged-out-content').show();
      }

    // 滑动开关mask
    $('#mask-on').click(function() {
        $('.mask').slideDown();
        $('body').css('overflow', 'hidden');
    });

    $('#mask-off').click(function() {
        $('.mask').slideUp();
        $('body').css('overflow', 'auto');
    });
    
    $('#username').click(function() {
        if (window.location.pathname.includes('index.html')) {
            window.location.href = 'page/introduction/introduction.html';
        } else {
            window.location.href = '../introduction/introduction.html';
        }
    });
    
    $('#user-icon').click(function() {
        if (window.location.pathname.includes('index.html')) {
            window.location.href = 'page/introduction/introduction.html';
        } else {
            window.location.href = '../introduction/introduction.html';
        }
    });
   
});

// 检查登录状态
const checkLoginStatus = () => {
    console.log('检查登录状态');
    const isLoggedIn = sessionStorage.getItem('username');
    return isLoggedIn
}

const checkGeoInfo = () => {
    const city = localStorage.getItem('city');
    const cityExpiration = localStorage.getItem('cityExpiration');
    const weather = localStorage.getItem('weather');
    if (city && cityExpiration) {
        const currentTime = Date.now();
        if (currentTime < cityExpiration) {
            $('#city').text(city);
            $('#weather').attr('class', 'iconfont ' + weather);
        } else {
            // City data has expired
            getGeoLocation();

        }
    } else {
        // City data does not exist in local storage
        getGeoLocation();
    }
}

const getGeoLocation = () => {
    // 先判断是否读取过地址
    
    let geocoder = new AMap.Geocoder({}); // 获取地理编码与逆地理编码类 实例
    // 判断是否存在navigator.geolocation
    let city = {}, weather = {};
    
    if(navigator && navigator.geolocation) {
        // 开始定位
        navigator.geolocation.getCurrentPosition(function(position) {
            let latitude = position.coords.latitude;// 获取纬度
            let longitude = position.coords.longitude;// 获取经度
            // console.log("Latitude: " + latitude + ", Longitude: " + longitude);
            // 获取到的是gps 定位 使用高德的经纬度转换
            // https://lbs.amap.com/api/webservice/guide/api/convert 这是经纬度转换的地址可以看下有什么参数
            key = 'a94480a4505e1ed34318766f4d4017c3';
        
            $.ajax({
                url: 'https://restapi.amap.com/v3/geocode/regeo?key=a94480a4505e1ed34318766f4d4017c3',
                type: 'get',
                data: {
                    location: longitude+','+latitude,
                    output: "JSON",
                },
                success:function(res){
                    city = res.regeocode.addressComponent;
                    weather = getWeather(city);
                    city.weather = weather;
                    console.log(city);
                    $('#city').text(city.city);
                    localStorage.setItem('city', city.city); // Cache city in local storage
                    // Cache city for three hours
                    const threeHours = 3 * 60 * 60 * 1000; // Convert three hours to milliseconds
                    const expirationTime = Date.now() + threeHours;
                    localStorage.setItem('cityExpiration', expirationTime);
                   
                }
            })
        },function(err){
            console.log(err);
        },{
            enableHighAcuracy: true, //位置是否精确获取
            timeout: 5000,            //获取位置允许的最长时间
            maximumAge: 1000          //多久更新获取一次位置
        });
    }
   
}

const getWeather = (city) => {
    let cityCode = city.adcode;
    let weather = '';
    
    $.ajax({
        url: 'https://restapi.amap.com/v3/weather/weatherInfo?key=a94480a4505e1ed34318766f4d4017c3',
        type: 'get',
        data: {
            city: cityCode,
            output: "JSON",
        },
        success:function(res){
            weather = res.lives[0].weather;
            console.log(weather);
            let iconClass = 'icon-zanwuxinxi';
            if(weather == '晴'){
                iconClass = 'icon-qing';
            }else if(weather == '多云'){
                iconClass = 'icon-duoyun';
            }else if(weather == '阴'){
                iconClass = 'icon-yin';
            }else if(weather == '雨'){
                iconClass = 'icon-dayu';
            }else if(weather == '雪'){
                iconClass = 'icon-daxue';
            }else if(weather == '雷阵雨'){
                iconClass = 'icon-leizhenyu';
            }
            $('#weather').attr('class', 'iconfont ' + iconClass);
            localStorage.setItem('weather', iconClass); 
        }
    })
}